package com.zwz.exception;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {


//    @Autowired
//    private AlertService alertService;

    @ExceptionHandler(DuplicateKeyException.class)
    public ResponseEntity<String> handleDuplicateKey(DuplicateKeyException ex, WebRequest request) {
        // 记录错误日志
        String errorMsg = "Duplicate key error: " + ex.getRootCause().getMessage();
        log.error(errorMsg);

        // 提取关键信息（例如冲突的主键值）
        String conflictKey = extractConflictKey(ex.getMessage());

        // 触发告警
//        alertService.sendAlert("Duplicate Key Alert",
//                "冲突主键：" + conflictKey + "\n请求路径：" + request.getDescription(false));

        log.error("Duplicate Key Alert",
                "冲突主键：" + conflictKey + "\n请求路径：" + request.getDescription(false));

        return ResponseEntity.status(HttpStatus.CONFLICT).body(errorMsg);
    }

    private String extractConflictKey(String message) {
        // 使用正则提取 'Duplicate entry 'xxx' 中的 'xxx'
        Pattern pattern = Pattern.compile("Duplicate entry '(.*?)'");
        Matcher matcher = pattern.matcher(message);
        return matcher.find() ? matcher.group(1) : "未知键值";
    }
}